import React, { useState, useEffect, useCallback } from 'react';
import { useSearchParams } from 'react-router-dom';
import {
  Card, Table, Button, Select, DatePicker, Space, Row, Col, Statistic, Spin,
  message, Tabs, Form, Input, Modal, Tag, Tooltip, Progress, Alert, Divider,
  Typography, Empty, Breadcrumb
} from 'antd';
import ResizableTable from './ResizableTable';
import {
  BarChartOutlined, LineChartOutlined, PieChartOutlined, DownloadOutlined,
  FilterOutlined, ReloadOutlined, CalendarOutlined, FileExcelOutlined, 
  FilePdfOutlined, RiseOutlined, FallOutlined, TableOutlined
} from '@ant-design/icons';
import { Line, Column, Pie } from '@ant-design/plots';
import api from '../utils/api';
import dayjs from 'dayjs';
import { getErrorMessage, getSuccessMessage, ERROR_TYPES, SUCCESS_TYPES } from '../utils/i18n';

const { Title, Text } = Typography;
const { RangePicker } = DatePicker;
const { Option } = Select;

const REPORT_CONFIG = {
  sales: {
    name: '销售报表',
    bgColor: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    reports: {
      daily: { name: '日销售报表', description: '每日销售数据统计' },
      monthly: { name: '月销售报表', description: '月度销售数据汇总' },
      product: { name: '产品销售报表', description: '产品销售明细分析' },
    }
  },
  user: {
    name: '用户报表',
    bgColor: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
    reports: {
      growth: { name: '用户增长报表', description: '用户增长趋势分析' },
      activity: { name: '用户活跃度报表', description: '用户活跃度统计' },
    }
  },
  order: {
    name: '订单报表',
    bgColor: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
    reports: {
      summary: { name: '订单汇总报表', description: '订单数据汇总统计' },
      trend: { name: '订单趋势报表', description: '订单趋势变化分析' },
    }
  },
};

function ReportChart({ data, chartType, title }) {
  const renderChart = () => {
    const config = { data, xField: 'date', yField: 'value', smooth: true };
    switch (chartType) {
      case 'line': return <Line {...config} />;
      case 'column': return <Column {...config} />;
      case 'pie': return <Pie {...config} angleField="value" colorField="type" />;
      default: return <Line {...config} />;
    }
  };
  return <Card title={title}>{renderChart()}</Card>;
}

function ReportTable({ data, columns, loading, title }) {
  return (
    <Card title={title}>
      <ResizableTable
        dataSource={data}
        columns={columns}
        loading={loading}
        pagination={{ pageSize: 10, showTotal: (total) => `共 ${total} 条` }}
      />
    </Card>
  );
}

function ReportExport({ reportKey, filters }) {
  const [exporting, setExporting] = useState(false);

  const handleExport = async (format) => {
    setExporting(true);
    try {
      const response = await api.post('/reports/export', 
        { reportKey, format, filters }, 
        { responseType: 'blob' }
      );
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `${reportKey}_${dayjs().format('YYYY-MM-DD')}.${format}`);
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(url);
      message.success(getSuccessMessage('REPORTS', SUCCESS_TYPES.REPORT_EXPORT_SUCCESS));
    } catch (error) {
      message.error(getErrorMessage('REPORTS', ERROR_TYPES.REPORT_EXPORT_FAILED));
    } finally {
      setExporting(false);
    }
  };

  return (
    <Card title="数据导出">
      <Space direction="vertical" style={{ width: '100%' }}>
        <Button icon={<FileExcelOutlined />} onClick={() => handleExport('xlsx')} loading={exporting} block>Excel</Button>
        <Button icon={<FilePdfOutlined />} onClick={() => handleExport('pdf')} loading={exporting} block>PDF</Button>
      </Space>
    </Card>
  );
}

function Reports() {
  const [searchParams] = useSearchParams();
  const category = searchParams.get('category') || 'sales';
  const type = searchParams.get('type') || 'daily';

  const [reportData, setReportData] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [filters, setFilters] = useState({ dateRange: [dayjs().subtract(7, 'day'), dayjs()] });

  const currentCategory = REPORT_CONFIG[category];
  const currentReport = currentCategory?.reports[type];
  const reportKey = `${category}_${type}`;

  const fetchReportData = useCallback(async (currentFilters) => {
    if (!currentReport) return;
    setLoading(true);
    setError(null);
    try {
      const params = {
        startDate: currentFilters.dateRange ? currentFilters.dateRange[0].format('YYYY-MM-DD') : undefined,
        endDate: currentFilters.dateRange ? currentFilters.dateRange[1].format('YYYY-MM-DD') : undefined,
      };
      const response = await api.get(`/reports/${reportKey}`, { params });
      setReportData(response.data);
    } catch (err) {
      setError(getErrorMessage('REPORTS', ERROR_TYPES.REPORT_LOAD_FAILED));
      message.error(getErrorMessage('REPORTS', ERROR_TYPES.REPORT_LOAD_FAILED));
    } finally {
      setLoading(false);
    }
  }, [reportKey, currentReport]);

  useEffect(() => {
    fetchReportData(filters);
  }, [fetchReportData, filters]);

  const handleFiltersChange = (newFilters) => {
    setFilters(newFilters);
  };

  if (!currentReport) {
    return (
      <div style={{ padding: 24 }}>
        <Empty description="请从菜单选择要查看的报表" />
      </div>
    );
  }

  return (
    <div style={{ padding: 24, background: '#f5f5f5' }}>
      <Card 
        style={{ marginBottom: 24, background: currentCategory.bgColor, color: 'white', border: 'none' }}
        bodyStyle={{ padding: '16px 24px' }}
      >
        <Breadcrumb separator={<span style={{ color: 'rgba(255,255,255,0.7)' }}>/</span>}>
          <Breadcrumb.Item><span style={{ color: 'white' }}><BarChartOutlined /> 报表管理</span></Breadcrumb.Item>
          <Breadcrumb.Item><span style={{ color: 'white' }}>{currentCategory.name}</span></Breadcrumb.Item>
          <Breadcrumb.Item><span style={{ color: 'white' }}>{currentReport.name}</span></Breadcrumb.Item>
        </Breadcrumb>
      </Card>

      <Card style={{ marginBottom: 24 }}>
        <Space>
          <RangePicker value={filters.dateRange} onChange={(dates) => handleFiltersChange({ ...filters, dateRange: dates })} />
          <Button type="primary" icon={<ReloadOutlined />} onClick={() => fetchReportData(filters)} loading={loading}>刷新</Button>
        </Space>
      </Card>

      {loading && <div style={{ textAlign: 'center', padding: 50 }}><Spin size="large" /></div>}
      {error && <Alert message="错误" description={error} type="error" showIcon />}

      {reportData && !loading && !error && (
        <Row gutter={[24, 24]}>
          <Col span={18}>
            <Space direction="vertical" style={{ width: '100%' }} size="large">
              <ReportChart data={reportData.chartData} chartType={reportData.chartType} title={`${currentReport.name} - 趋势图`} />
              <ReportTable data={reportData.tableData} columns={reportData.columns} loading={loading} title={`${currentReport.name} - 详细数据`} />
            </Space>
          </Col>
          <Col span={6}>
            <Space direction="vertical" style={{ width: '100%' }} size="middle">
              <ReportExport reportKey={reportKey} filters={filters} />
              <Card title="快速统计">
                <Statistic title="总计" value={reportData.summary?.total} prefix={<RiseOutlined />} />
                <Statistic title="增长率" value={reportData.summary?.growth} suffix="%" valueStyle={{ color: reportData.summary?.growth >= 0 ? '#3f8600' : '#cf1322' }} />
              </Card>
            </Space>
          </Col>
        </Row>
      )}
    </div>
  );
}

export default Reports;